package com.atguigu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    //上传头像到oss
    @Override
    public String uploadFileAvtar(MultipartFile file) throws IOException {

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ConstantPropertiesUtils.END_POIND;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        InputStream inputStream = file.getInputStream();
        //1 为防止文件覆盖，需要加入文件随机值
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = file.getOriginalFilename();
        fileName = uuid + fileName;
        //2 把文件按照日期进行分类
        //获取当前日期
        String datePath = new DateTime().toString("yyyy/MM/dd");
        fileName = datePath + "/" + fileName;
        //第一个参数，bucket名称
        //第二个参数，上传到oss文件路径和文件名称 aa/bb/1.jpg
        //第三个参数，上传文件输入流
        ossClient.putObject(bucketName, fileName, inputStream);
        ossClient.shutdown();
        //https://edu-55555.oss-cn-beijing.aliyuncs.com/13.jpg
        String url = "https://" + bucketName + "." + endpoint + "/" + fileName;

        return url;
    }
}
